package cn.flying.base.mybatis.thread;

import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * @description: 线程池工具类
 * @author: lvyong
 * @date: 2022年11月10日 19:34
 * @version: 1.0
 */
@Component
public class ThreadPoolExecUtil implements InitializingBean {

    private ThreadPoolExecutor executor;

    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     *
     * @throws Exception in the event of misconfiguration (such as failure to set an
     *                   essential property) or if initialization fails for any other reason
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        int processors = Runtime.getRuntime().availableProcessors();
        if (Objects.isNull(executor)) {
            executor = new ThreadPoolExecutor(processors * 2, processors * 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200));
        }
    }

    public Future<?> execute(Runnable runnable) {
        return executor.submit(runnable);
    }
}
